﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

using Kxzz.Common;
using DevComponents.DotNetBar.Rendering;
using KxzzEntity.SettingEntity;
using Kaixin001.Common;
using Kaixin001.XmlUtil;
using KxzzEntity.Enums;
using Kaixin001.ProxyUtil;
using System.Threading;
using System.IO;

namespace Kxzz.SettingForm
{
    public partial class frmProxySetting : DevComponents.DotNetBar.Office2007Form
    {
        #region 变量
        private IniHelper iniHelper = new IniHelper(Application.StartupPath + "//Config//config.ini");
        private ProxySettingEntity proxyEntity = null;

        delegate void DelegateShowMessage(string str);
        delegate void DelegateVoid();

        Thread threadTest = null;
        Thread threadGetProxyList = null;
        /// <summary>
        /// 代理列表
        /// </summary>
        DataTable dt = new DataTable();

        DelegateShowMessage delegateShowMessage = null;
        #endregion

        #region 初始化构造函数
        public frmProxySetting()
        {
            InitializeComponent();

            #region 读取窗体皮肤设置
            if (this.iniHelper.read("Setup", "skin") != "")
            {
                eOffice2007ColorScheme colorScheme = (eOffice2007ColorScheme)Enum.Parse(typeof(eOffice2007ColorScheme), this.iniHelper.read("Setup", "skin"));
                this.Office2007ColorTable = colorScheme;
            }
            #endregion

            delegateShowMessage = new DelegateShowMessage(this.ShowMessage);
            this.dgvProxyList.AutoGenerateColumns = false;
        }

        private void frmProxySetting_Load(object sender, EventArgs e)
        {
            ProxyInit();
        }
        #endregion

        #region 界面操作
        private void dgvProxyList_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1)
                {
                    string strIP = this.dgvProxyList.Rows[e.RowIndex].Cells[0].Value as string;
                    string strPort = this.dgvProxyList.Rows[e.RowIndex].Cells[1].Value as string;
                    this.cbProxyType.SelectedIndex = 2;
                    this.txtIp.Text = strIP;
                    this.txtPort.Text = strPort;
                }
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                    ex.Message,
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnGetProxyList_Click(object sender, EventArgs e)
        {
            try
            {
                DelegateVoid delegateGetProxyList = new DelegateVoid(this.GetProxyList);
                threadGetProxyList = new Thread(new ThreadStart(delegateGetProxyList));
                threadGetProxyList.Start();
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                    ex.Message,
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void cbProxyType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.cbProxyType.SelectedIndex == 0)
                {
                    this.txtIp.Text = string.Empty;
                    this.txtPort.Text = string.Empty;

                    this.txtIp.Enabled = false;
                    this.txtPort.Enabled = false;
                    this.txtUserName.Enabled = false;
                    this.txtPassWord.Enabled = false;
                }
                else if (this.cbProxyType.SelectedIndex == 1)
                {
                    WebProxy proxy = WebProxy.GetDefaultProxy();

                    if (proxy.Address != null)
                    {
                        this.txtIp.Text = proxy.Address.Host;
                        this.txtPort.Text = proxy.Address.Port.ToString();
                    }

                    this.txtIp.Enabled = false;
                    this.txtPort.Enabled = false;
                    this.txtUserName.Enabled = true;
                    this.txtPassWord.Enabled = true;
                }
                else if (this.cbProxyType.SelectedIndex == 2)
                {

                    this.txtIp.Text = string.Empty;
                    this.txtPort.Text = string.Empty;

                    if (this.proxyEntity !=null)
                    {
                        this.txtIp.Text = proxyEntity.Ip;
                        this.txtPort.Text = proxyEntity.Port.ToString();
                    }

                    this.txtIp.Enabled = true;
                    this.txtPort.Enabled = true;
                    this.txtUserName.Enabled = true;
                    this.txtPassWord.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                    ex.Message,
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtIp.Text) ||
                     string.IsNullOrEmpty(this.txtPort.Text))
                {
                    this.BeginInvoke(delegateShowMessage, new object[] { "" });
                    DevComponents.DotNetBar.MessageBoxEx.Show(
                            "请先设置代理服务器，再测试！",
                            "提示",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    return;
                }

                DelegateVoid delegateTest = new DelegateVoid(this.Test);
                threadTest = new Thread(new ThreadStart(delegateTest));
                threadTest.Start();
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                    ex.Message,
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                ProxySettingEntity setting = this.GetProxySetting();
                bool result = XmlHelper.XmlSerialize(Init.ProxySettingPath, setting, typeof(ProxySettingEntity));
                if (result)
                {
                    Init.Kaixin001Helper.Proxy = setting;
                    this.btnCancel_Click(sender, e);
                }
                else
                {
                    DevComponents.DotNetBar.MessageBoxEx.Show(
                           "保存代理信息失败！",
                           "提示",
                           MessageBoxButtons.OK,
                           MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                    ex.Message,
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Form mainForm = this.ParentForm;
            mainForm.Close();
        }
        #endregion

        #region PrivateMethod

        /// <summary>
        /// 初始化代理信息
        /// </summary>
        private void ProxyInit()
        {
            if (File.Exists(Init.ProxySettingPath))
            {
                ProxySettingEntity proxyEntity = XmlHelper.XmlDeserialize(Init.ProxySettingPath, typeof(ProxySettingEntity)) as ProxySettingEntity;

                if (proxyEntity != null)
                {
                    this.proxyEntity = proxyEntity;
                    if (proxyEntity.ProxyType != 0)
                    {
                        Init.Kaixin001Helper.Proxy = proxyEntity;
                    }
                    else
                    {
                        Init.Kaixin001Helper.Proxy = null;
                        this.proxyEntity = null;
                    }
                    this.cbProxyType.SelectedIndex = proxyEntity.ProxyType;
                }
            }
            else
            {
                this.cbProxyType.SelectedIndex = 0;
            }
        }

        private void ShowMessage(string message)
        {
            this.lblInformation.Top = 0;
            this.lblInformation.Text = message;
        }

        /// <summary>
        /// 测试代理
        /// </summary>
        private void Test()
        {
            DelegateVoid delegateVoid = new DelegateVoid(this.EnableControl);

            this.BeginInvoke(delegateShowMessage, new object[] { "正在测试代理请稍后..." });
            this.Invoke(delegateVoid);

            try
            {
                ProxySettingEntity setting = this.GetProxySetting();

                if (BaseHttp.TestProxy(setting))
                {
                    this.BeginInvoke(delegateShowMessage, new object[] { "测试代理成功，此代理可以使用！" });
                }
                else
                {
                    this.BeginInvoke(delegateShowMessage, new object[] { "此代理无效！" });
                }
            }
            catch (Exception ex)
            {
                try
                {
                    this.BeginInvoke(delegateShowMessage, new object[] { ex.Message });
                }
                catch (Exception)
                { }
            }

            this.Invoke(delegateVoid);
            this.StopThread();
        }

        /// <summary>
        /// 获取代理列表
        /// </summary>
        private void GetProxyList()
        {
            DelegateVoid delegateEnablePanel = new DelegateVoid(this.EnableControl);

            try
            {
                this.BeginInvoke(delegateShowMessage, new object[] { "正在获取最新的代理列表，请稍后..." });
                this.Invoke(delegateEnablePanel);
                DelegateVoid delegateBindData = new DelegateVoid(this.BindDgv);
                this.Invoke(delegateBindData);
                this.BeginInvoke(delegateShowMessage, new object[] { "获取完毕！" });
            }
            catch (Exception ex)
            {
                try
                {
                    this.BeginInvoke(delegateShowMessage, new object[] { ex.Message });
                }
                catch (Exception)
                { }
            }
            finally
            {
                this.Invoke(delegateEnablePanel);
                this.StopThread();
            }
        }

        private void BindDgv()
        {
            dt = ProxyHelper.GetProxyList();
            this.dgvProxyList.DataSource = dt;
            this.dgvProxyList.Refresh();
        }

        private void EnableControl()
        {
            this.gpSettingMain.Enabled = !this.gpSettingMain.Enabled;
        }

        /// <summary>
        /// 关闭线程
        /// </summary>
        private void StopThread()
        {
            if (this.threadGetProxyList != null)
            {
                if (threadGetProxyList.ThreadState == ThreadState.Suspended)
                {
                    threadGetProxyList.Resume();
                }   
    
                this.threadGetProxyList.Abort();
                this.threadGetProxyList.Join();
                this.threadGetProxyList = null;
            }

            if (this.threadTest != null)
            {
                if (threadTest.ThreadState == ThreadState.Suspended)
                {
                    threadTest.Resume();
                }  

                this.threadTest.Abort();
                this.threadTest.Join();
                this.threadTest = null;
            }
        }

        /// <summary>
        /// 获取代理设置
        /// </summary>
        /// <returns></returns>
        public ProxySettingEntity GetProxySetting()
        {
            try
            {
                ProxySettingEntity setting = new ProxySettingEntity();

                if (this.txtIp.Text != "")
                {
                    setting.Ip = this.txtIp.Text;
                }
                if (this.txtPort.Text != "")
                {
                    setting.Port = int.Parse(this.txtPort.Text);
                }

                setting.ProxyType = this.cbProxyType.SelectedIndex;
                setting.UserName = this.txtUserName.Text;
                setting.Password = this.txtPassWord.Text;
                return setting;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
